package com.rtsapp.server.common.diskcache;

import com.rtsapp.server.utils.FileUtils;

import java.io.File;
import java.util.HashSet;
import java.util.Set;

/**
 * 使用单个小文件进行储存
 */
class SimpleFileDiskCache implements DiskCache{


    private final String cacheName;
    private final String dir;

    public SimpleFileDiskCache(String cacheName, String dir) {
        this.cacheName = cacheName;
        this.dir = dir;
    }


    @Override
    public Set<String> keys() {

        Set<String> keySet = new HashSet<>( );

        File f = new File( dir );
        String[] files = f.list();
        for( int i = 0; i < files.length; i++ ){
            keySet.add( files[i] );
        }

        return keySet;
    }

    @Override
    public byte[] get(String key) {
        File f = new File( dir, key );
        if( !f.exists() ){
            return null;
        }

        return FileUtils.readFile( f );
    }

    @Override
    public void set(String key, byte[] value) {
        FileUtils.writeFile( new File( dir, key ), value );
    }

    @Override
    public void append(String key, byte[] value ) {
        FileUtils.appendFile(new File(dir, key), value);
    }

    @Override
    public void remove(String key) {
        FileUtils.remove( new File( dir, key ) );
    }

}
